package com.yang.simple_rpc.client.discovery;

import com.alibaba.fastjson.JSON;
import com.yang.simple_rpc.common.constant.SimpleConstant;
import com.yang.simple_rpc.common.serializer.SimpleSerializer;
import com.yang.simple_rpc.common.service.Service;
import org.I0Itec.zkclient.ZkClient;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 *
 * 服务发现的具体实现类，具体定义了以zookeeper为注册中心的服务发现细则
 * @author : morikawaaaa
 * @date : 2022
 */
public class ZkServiceDiscovery implements ServiceDiscovery{
    private ZkClient zkClient;

    public ZkServiceDiscovery(String address){
        zkClient = new ZkClient(address);
        zkClient.setZkSerializer(new SimpleSerializer());
    }

    /**
     * 在zookeeper的service节点找到注册的所有服务，解码为json字符串，再转化为service对象，返回所有的服务对象列表
     * @param name
     * @return
     */
    @Override
    public List<Service> getService(String name) {
        String servicePath = SimpleConstant.ZK_SERVICE_PATH + SimpleConstant.PATH_DELIMITER + name + "/service";
        List<String> children = zkClient.getChildren(servicePath);
        return Optional.ofNullable(children).orElse(new ArrayList<>()).stream().map(s -> {
            String temp = null;
            try{
                temp = URLDecoder.decode(s, SimpleConstant.UTF_8);
            }catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }
            return JSON.parseObject(temp, Service.class);
        }).collect(Collectors.toList());
    }
}
